package ch.exm.storm.query.hibernate;

import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

import ch.exm.storm.query.QueryFactory;

public class HibernateQueryFactory implements QueryFactory {

	public HibernateQuery createQuery() {
		return createQuery(getSessionProvider());
	}
	
	public HibernateQuery createQuery(SessionProvider sessionProvider) {
		return new HibernateQuery(getHibernateConfiguration(), sessionProvider);
	}
	
	public HibernateQuery createQuery(Session session) {
		return new HibernateQuery(getHibernateConfiguration(), new DefaultSessionProvider(session));
	}

	// ////////////////////////////////////////////////////////////////////////
	// /// Configuration
	// ////////////////////////////////////////////////////////////////////////
	
	private HibernateConfiguration configuration;
	
	public void setConfiguration(Configuration configuration) {
		this.configuration = new HibernateConfiguration(configuration);
	}
	
	private HibernateConfiguration getHibernateConfiguration() {
		if (configuration == null) configuration = new HibernateConfiguration();
		return configuration;
	}
	
	// ////////////////////////////////////////////////////////////////////////
	// /// SessionProvider
	// ////////////////////////////////////////////////////////////////////////
	
	private SessionProvider sessionProvider;

	public SessionProvider getSessionProvider() {
		if (sessionProvider == null) {
			sessionProvider = new FactorySessionProvider(getHibernateConfiguration().getSessionFactory());
		}
		return sessionProvider;
	}

	public void setSessionProvider(SessionProvider sessionProvider) {
		this.sessionProvider = sessionProvider;
	}
}
